package cs2340.g21.wms;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import android.content.Context;
import android.util.Log;

/**
 * Writes and reads app session data to phone storage
 */
public class Session {
    private static final String LOG_TAG = "debugger";
    
    public boolean sessionExists(){
        return false;
    }
    
    /**
     * Writes the app data to data.wms
     * @param c the coordinator to write
     * @param context from which this method is called
     */
    public void writeSession(Coordinator c, Context context){
        try{
            FileOutputStream fos = context.openFileOutput("data.wms", Context.MODE_PRIVATE);
            OutputStream bos = new BufferedOutputStream(fos);
            ObjectOutputStream os = new ObjectOutputStream(bos);
            try{
                Log.d(LOG_TAG, "writing");
                os.writeObject(c);
            }
            finally{
                Log.d(LOG_TAG, "written");
                os.close();
            }
          }  
          catch(IOException ex){
            Log.d(LOG_TAG, "error with write");
          }
    }
    
    /**
     * Reads deserializes data from data.wms into a new coordinator
     * @param context from which this method is called
     * @return
     */
    public Coordinator readSession(Context context){
        Coordinator c = new Coordinator();
        try{
            FileInputStream fis = context.openFileInput("data.wms");
            InputStream bis = new BufferedInputStream(fis);
            ObjectInputStream is = new ObjectInputStream(bis);
            try{
              //deserialize
              Log.d(LOG_TAG, "reading");
              c = (Coordinator)is.readObject();
            }
            finally{
                Log.d(LOG_TAG, "read");
                is.close();
            }
          }
          catch(ClassNotFoundException ex){
            Log.d(LOG_TAG, "no class");
          }
          catch(IOException ex){
            Log.d(LOG_TAG, "error with file read");
          }
        return c;
    }
}
